<script setup>
import {ref} from "vue";
import {useRouter} from "vue-router";
import {resetPhone} from "@/apis/user";
import {sendResetPhoneSms} from "@/apis/sms";
import {Message} from "tdesign-mobile-vue";
import {useUserStore} from "@/stores/user";

const formData = ref({
  code: "",
  phone: ""
})
const store = useUserStore();
const router = useRouter();

function sendSmsFunc() {
  sendResetPhoneSms(store.user.phone)
      .then(res => {
        const {code, msg} = res.data;
        if (code === 1) {
          Message.success({
            content: '验证码已发送',
            context: document.querySelector('main'),
            duration: 2000,
            offset: [8, 8]
          });
        } else {
          Message.error({
            content: msg,
            context: document.querySelector('main'),
            duration: 2000,
            offset: [8, 8]
          });
        }
      })
}

function resetPwdFunc() {
  resetPhone(formData.value)
      .then(res => {
        const {code, msg} = res.data;
        if (code === 1) {
          Message.success({
            content: msg,
            context: document.querySelector('main'),
            duration: 2000,
            offset: [8, 8]
          });
          setTimeout(() => {
            store.userLogout();
            router.replace({
              name: 'login'
            })
          }, 2000);
        } else {
          Message.error({
            content: msg,
            context: document.querySelector('main'),
            duration: 2000,
            offset: [8, 8]
          });
        }
      })
}
</script>
<template>
  <main>
    <t-form @submit="resetPwdFunc" :labelWidth="100">
      <t-cell-group title="修改密码">
        <t-form-item label="验证码">
          <t-input borderless v-model="formData.code">
            <template #suffix>
              <t-button theme="primary" size="extra-small" @click="sendSmsFunc"> 发送验证码</t-button>
            </template>
          </t-input>
        </t-form-item>
        <t-form-item label="新手机号码">
          <t-input borderless v-model="formData.phone"></t-input>
        </t-form-item>
      </t-cell-group>
      <div style="padding: 8px;">
        <t-button theme="primary" block type="submit">保存</t-button>
      </div>
    </t-form>
  </main>
</template>